﻿using Common.Communal;
using MediatR;
using Product.API.ISerivces.Upload;
using Product.API.Write.Applications.Commands.Upload;

namespace Product.API.Write.Applications.CommandHandlers.Upload
{
    /// <summary>
    /// 文件上传命令处理
    /// </summary>
    public class UploadFileCommandHandler : IRequestHandler<UploadFileCommand, ApiResult<string>>
    {
        /// <summary>
        /// 上传服务
        /// </summary>
        private readonly IUploadSerivces uploadSerices;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="uploadSerices">上传服务</param>
        public UploadFileCommandHandler(IUploadSerivces uploadSerices)
        {
            this.uploadSerices = uploadSerices;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<string>> Handle(UploadFileCommand request, CancellationToken cancellationToken)
        {
            ApiResult<string> result = new ApiResult<string>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();

            try
            {
                // 获取扩展名
                string fileExtension = Path.GetExtension(request.file.FileName).ToLower();

                string data = uploadSerices.UploadFile(request.file, request.customFolder);
                result.Data = data;

                return Task.FromResult(result);
            }
            catch (Exception ex)
            {
                result.Code = EnumCode.Fail;
                result.Message = EnumCode.Fail.ToString();
                result.Data = ex.ToString();
                return Task.FromResult(result);
            }
        }
    }
}
